#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：backend.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/14 上午9:30 
"""

import time
import sqlite3
import random
from multiprocessing import Process, Queue, Value

from 进程通讯.前后端分离尝试.database import DatabaseManager


class TCPClient:
    def send_message(self, message):
        # 模拟发送 TCP 报文
        print(f"Sent TCP message: {message}")
        return f"Response to {message}"

def data_reader(data_queue, db_path):
    db = DatabaseManager(db_path)
    while True:
        data = db.get_data()
        data_queue.put(data)
        print("Data read and sent to main process")
        time.sleep(2)

def task_processor(task_queue, db_path):
    db = DatabaseManager(db_path)
    tcp = TCPClient()
    while True:
        if not task_queue.empty():
            task = task_queue.get()
            if task["type"] == "update_db":
                db.update_data(task["key"], task["value"])
                print(f"Database updated: key={task['key']}, value={task['value']}")
            elif task["type"] == "send_tcp":
                response = tcp.send_message(task["message"])
                print(f"Received response: {response}")
        time.sleep(1)

def value_monitor(task_queue, value_queue, monitored_value, trigger_value, trigger_queue):
    while True:
        # 等待值生成器生成新值
        if not value_queue.empty():
            new_value = value_queue.get()
            monitored_value.value = new_value
            print(f"Monitored value updated: {monitored_value.value}")

            # 检查触发条件
            if new_value == trigger_value:
                # 触发任务
                task_queue.put({"type": "update_db", "key": 1, "value": "Triggered by monitor"})
                print("Send db update task")

        time.sleep(0.1)

def generate_value(value_queue):
    while True:
        value = random.randint(1, 5)  # 模拟生成动态值
        value_queue.put(value)
        print(f"Generated new value: {value}")
        time.sleep(3)

def start_backend(data_queue, task_queue, db_path):
    data_reader_process = Process(target=data_reader, args=(data_queue, db_path))
    data_reader_process.start()

    task_processor_process = Process(target=task_processor, args=(task_queue, db_path))
    task_processor_process.start()

    return data_reader_process, task_processor_process